import { Component, OnInit, Injector, ViewChild, Output, EventEmitter } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    EditDtoExtensionsItem,
    StockZT_IntoBillItemServiceProxy,
    Stock_IntoMarketBaseEditDto
} from '@shared/service-proxies/stock-service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'createOrEditMarketIntoBillModal',
    templateUrl: './create-or-edit-market-into-bill-modal.component.html'
})
export class CreateOrEditMarketIntoBillModalComponent extends AppComponentBase {
    constructor(injector: Injector, private _billService: StockZT_IntoBillItemServiceProxy) {
        super(injector);
    }

    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    @Output() clearQuery: EventEmitter<any> = new EventEmitter<any>();
    active = false;
    saving = false;

    editDto: Stock_IntoMarketBaseEditDto;
    extensions: Array<EditDtoExtensionsItem>;
    optionAll;
    f_ReceiveDate: Date;

    show(id?: string): void {
        this.active = true;
        this._billService.getIntoMarketBaseForEditExtension(id).subscribe(result => {
            let optionAll = {};

            if (result.selects) {
                result.selects.forEach(el => {
                    optionAll[el.label] = el.value;
                });
            }
            this.optionAll = optionAll;
            this.editDto = result.dto;
            this.extensions = result.items;
            console.log(result);
            this.modal.show();
        });
    }

    save(): void {
        this.saving = true;
        console.log(this.editDto);

        this._billService
            .createOrUpdateIntoMarketBase(this.editDto)
            .pipe(
                finalize(() => {
                    this.saving = false;
                })
            )
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.clearQuery.emit();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
